package com.unionfetch.content_home.ui.account

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.transition.TransitionManager
import android.view.KeyEvent
import android.view.View
import android.view.animation.RotateAnimation
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.widget.NestedScrollView
import androidx.core.widget.addTextChangedListener
import com.unionfetch.content_home.R
import com.unionfetch.content_home.bean.AccountType
import com.unionfetch.content_home.bean.request.AddLiveAccountRequest
import com.unionfetch.content_home.contract.AccountContract
import com.unionfetch.content_home.presenter.AccountPresenter
import com.unionfetch.content_home.ui.dialog.CustomSelectDialog
import com.unionfetch.content_home.ui.dialog.CustomTipDialog
import com.unionfetch.content_home.ui.fragment.HomeFragment
import com.unionftech.common.R.color
import com.unionftech.common.R.drawable
import com.unionftech.common.R.string
import com.unionftech.common.base.IUpdate
import com.unionftech.common.base.mvp.annitation.InjectPresenter
import com.unionftech.common.base.mvp.impl.BaseMvpActivity
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.bean.toast
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.common.common.bean.Platform
import com.unionftech.common.common.bean.TradePlatform
import com.unionftech.common.common.bean.UserGroupInfo
import com.unionftech.common.common.contract.CommonContract
import com.unionftech.common.common.language.DynamicResourceManager
import com.unionftech.common.common.presenter.CommonPresenter
import com.unionftech.common.utils.CheckInputUtil
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.utils.RegexUtils
import com.unionftech.common.utils.SignUtils
import com.unionftech.common.utils.ToastUtils
import com.unionftech.common.utils.autoSize

class AddLiveTradeAccountActivity : BaseMvpActivity(), IUpdate, CommonContract.IPlatformView,
    CommonContract.ICurrencyView, CommonContract.IAccountTypeView,
    AccountContract.IAddLiveAccountView {

    private val mBtnConfirm by lazy { findViewById<Button>(R.id.btn_confirm) }
    private val mIvClearInvitationCode by lazy { findViewById<ImageView>(R.id.iv_clear_invitation_code) }
    private val mEtInvitationCode by lazy { findViewById<EditText>(R.id.et_invitation_code) }
    private val mTvInvitationCodeError by lazy { findViewById<TextView>(R.id.tv_invitation_code_error) }
    private val mRlInvitationCode by lazy { findViewById<RelativeLayout>(R.id.rl_invitation_code) }
    private val mIvInvitationArrow by lazy { findViewById<ImageView>(R.id.iv_invitation_arrow) }
    private val mTvInvitationCodeTitle by lazy { findViewById<TextView>(R.id.tv_invitation_code_title) }
    private val mTvRemarkCountTip by lazy { findViewById<TextView>(R.id.tv_remark_count_tip) }
    private val mEtRemark by lazy { findViewById<EditText>(R.id.et_remark) }
    private val mTvRemarkTitle by lazy { findViewById<TextView>(R.id.tv_remark_title) }
    private val mLlRemark by lazy { findViewById<LinearLayout>(R.id.ll_remark) }
    private val mTvConfirmTradingPasswordError by lazy { findViewById<TextView>(R.id.tv_confirm_trading_password_error) }
    private val mIvClearConfirmTradingPassword by lazy { findViewById<ImageView>(R.id.iv_clear_confirm_trading_password) }
    private val mIvShowConfirmTradingPassword by lazy { findViewById<ImageView>(R.id.iv_show_confirm_trading_password) }
    private val mEtConfirmTradingPassword by lazy { findViewById<EditText>(R.id.et_confirm_trading_password) }
    private val mTvConfirmTradingPasswordTitle by lazy { findViewById<TextView>(R.id.tv_confirm_trading_password_title) }
    private val mTvTradingPasswordError by lazy { findViewById<TextView>(R.id.tv_trading_password_error) }
    private val mIvClearTradingPassword by lazy { findViewById<ImageView>(R.id.iv_clear_trading_password) }
    private val mIvShowTradingPassword by lazy { findViewById<ImageView>(R.id.iv_show_trading_password) }
    private val mEtTradingPassword by lazy { findViewById<EditText>(R.id.et_trading_password) }
    private val mTvTradingPasswordTitle by lazy { findViewById<TextView>(R.id.tv_trading_password_title) }
    private val mEtAccountCurrency by lazy { findViewById<TextView>(R.id.et_account_currency) }
    private val mTvAccountCurrencyTitle by lazy { findViewById<TextView>(R.id.tv_account_currency_title) }
    private val mLlAccountCurrency by lazy { findViewById<LinearLayout>(R.id.ll_account_currency) }
    private val mEtAccountType by lazy { findViewById<TextView>(R.id.et_account_type) }
    private val mTvAccountTypeTitle by lazy { findViewById<TextView>(R.id.tv_account_type_title) }
    private val mLlAccountType by lazy { findViewById<LinearLayout>(R.id.ll_account_type) }
    private val mEtTradePlatform by lazy { findViewById<TextView>(R.id.et_trade_platform) }
    private val mTvTradePlatformTitle by lazy { findViewById<TextView>(R.id.tv_trade_platform_title) }
    private val mLlTradePlatform by lazy { findViewById<LinearLayout>(R.id.ll_trade_platform) }
    private val mScPage by lazy { findViewById<NestedScrollView>(R.id.sc_page) }

    @InjectPresenter
    private lateinit var mCommonPresenter: CommonPresenter

    @InjectPresenter
    private lateinit var mAccountPresenter: AccountPresenter

    //平台选项
    private var mSystemPlatformList: List<TradePlatform>? = null
    private var mGroupInfo: UserGroupInfo? = null
    private val mPlatformList = mutableListOf<TradePlatform>()
    private var mPlatformIndex = -1
    private var mIsShowSelectDialog: Boolean = false

    //账户类型选项
    private val mAccountTypeList = mutableListOf<Int>()
    private var mAccountTypeIndex = -1

    //币种选项
    private var mSystemCurrencyList: List<String>? = null
    private val mCurrencyList = mutableListOf<String>()
    private var mCurrencyIndex = -1
    private var mPublicKeyStr: String = ""
    private var mCurrentInvitationCode = ""

    companion object {
        private const val TAG = "AddLiveTradeAccountActivity"
        private const val PLATFORM_MT4 = 1

        private const val PLATFORM_MT5 = 2

        @JvmStatic
        fun startThis(context: Context) {
            Intent(context, AddLiveTradeAccountActivity::class.java).apply {
                if (context !is Activity) {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }
                context.startActivity(this)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun initLayout() = R.layout.activity_add_live_trade_account

    override fun initLanguageText() {
        super.initLanguageText()
        mTvTradePlatformTitle.text = DynamicResourceManager.getString(string.trading_platform)
        mEtTradePlatform.hint = DynamicResourceManager.getString(string.please_select)
        mTvAccountTypeTitle.text = DynamicResourceManager.getString(string.trading_account_type)
        mEtAccountType.hint = DynamicResourceManager.getString(string.please_select)
        mTvAccountCurrencyTitle.text = DynamicResourceManager.getString(string.account_currency)
        mEtAccountCurrency.hint = DynamicResourceManager.getString(string.please_select)
        mTvTradingPasswordTitle.text = DynamicResourceManager.getString(string.trading_password)
        mEtTradingPassword.hint = DynamicResourceManager.getString(string.please_input)
        mTvConfirmTradingPasswordTitle.text =
            DynamicResourceManager.getString(string.confirm_trading_password)
        mEtConfirmTradingPassword.hint = DynamicResourceManager.getString(string.please_input)
        mTvRemarkTitle.text = DynamicResourceManager.getString(string.apply_remark)
        mEtRemark.hint = DynamicResourceManager.getString(string.please_input)
        mTvInvitationCodeTitle.text = DynamicResourceManager.getString(string.invitation_code)
        mEtInvitationCode.hint = DynamicResourceManager.getString(string.please_input)
        mBtnConfirm.text = DynamicResourceManager.getString(string.confirm)
    }

    override fun setListener() {
        super.setListener()
        mEtTradePlatform.setOnClickListener(this)
        mEtAccountType.setOnClickListener(this)
        mEtAccountCurrency.setOnClickListener(this)
        mIvClearTradingPassword.setOnClickListener(this)
        mIvShowTradingPassword.setOnClickListener(this)
        addTextChangeListener(mEtTradingPassword, mIvClearTradingPassword)
        addFocusChangeListener(mEtTradingPassword, mIvClearTradingPassword)

        mIvClearConfirmTradingPassword.setOnClickListener(this)
        mIvShowConfirmTradingPassword.setOnClickListener(this)
        addTextChangeListener(mEtConfirmTradingPassword, mIvClearConfirmTradingPassword)
        addFocusChangeListener(mEtConfirmTradingPassword, mIvClearConfirmTradingPassword)

        mIvClearInvitationCode.setOnClickListener(this)
        mTvInvitationCodeTitle.setOnClickListener(this)
        mIvInvitationArrow.setOnClickListener(this)
        addTextChangeListener(mEtInvitationCode, mIvClearInvitationCode)
        addFocusChangeListener(mEtInvitationCode, mIvClearInvitationCode)
        addTextChangeListener(mEtRemark)

        mBtnConfirm.setOnClickListener(this)

    }

    private fun addTextChangeListener(editText: EditText, clearView: ImageView? = null) {
        editText.addTextChangedListener { text ->
            if (text.toString().contains(" ")) {
                val str = text?.toString()?.split(" ")
                val sb = StringBuffer()
                for (i in 0 until str?.size!!) {
                    sb.append(str[i])
                }
                editText.setText(sb.toString())
                editText.setSelection(sb.toString().length)
            }
            setClearView(editText.text, clearView)
            setButtonEnable()
            if (editText == mEtConfirmTradingPassword) {
                if (checkInput(editText)) {
                    checkPasswordEquals()
                }
            } else if (editText == mEtTradingPassword) {
                if (!TextUtils.isEmpty(mEtConfirmTradingPassword.text) && checkInput(
                        mEtConfirmTradingPassword
                    )
                ) {
                    checkPasswordEquals()
                }
            } else if (editText == mEtRemark) {
                mTvRemarkCountTip.text = "${mEtRemark.text.length}/200"
            }
        }
    }

    private fun addFocusChangeListener(
        editText: EditText, clearView: ImageView? = null
    ) {
        editText.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                //去除错误边框展示
                editText.isSelected = false
                setClearView(editText.text, clearView)
                if (editText == mEtInvitationCode) {
                    mTvInvitationCodeError.visibility = View.INVISIBLE
                    mTvInvitationCodeError.text = ""
                    mEtInvitationCode.isSelected = false
                }
            } else {
                clearView?.visibility = View.GONE
                if (checkInput(editText)) {
                    if (mEtConfirmTradingPassword == editText) {
                        checkPasswordEquals()
                    }
                }
                if (editText == mEtInvitationCode) {
                    queryPlatform(false)
                    queryAccountType(false)
                }
            }
        }
    }

    private fun setClearView(text: Editable?, clearView: ImageView?) {
        if (!TextUtils.isEmpty(text)) {
            clearView?.visibility = View.VISIBLE
        } else {
            clearView?.visibility = View.GONE
        }
    }

    private fun checkInput(editText: EditText): Boolean {
        when (editText) {
            mEtTradingPassword -> return CheckInputUtil.checkInput(
                mEtTradingPassword.text.toString(),
                RegexUtils.TRADE_PASSWORD_REGEX,
                mEtTradingPassword,
                mTvTradingPasswordError,
                string.password_empty,
                string.password_regular_tip
            )

            mEtConfirmTradingPassword -> return CheckInputUtil.checkInput(
                mEtConfirmTradingPassword.text.toString(),
                RegexUtils.TRADE_PASSWORD_REGEX,
                mEtConfirmTradingPassword,
                mTvConfirmTradingPasswordError,
                string.password_empty,
                string.password_regular_tip
            )
        }
        return true
    }

    private fun checkPasswordEquals() {
        if (!TextUtils.equals(
                mEtTradingPassword.text, mEtConfirmTradingPassword.text
            )
        ) {
            mTvConfirmTradingPasswordError.visibility = View.VISIBLE
            mTvConfirmTradingPasswordError.text =
                DynamicResourceManager.getString(string.trading_password_inconsistency)
        } else {
            mTvConfirmTradingPasswordError.visibility = View.INVISIBLE
        }
    }

    private fun setButtonEnable() {
        mBtnConfirm.isEnabled = checkButtonEnable()
    }

    private fun checkButtonEnable(): Boolean {
        return (mPlatformIndex != -1 && mAccountTypeIndex != -1 && mCurrencyIndex != -1 && !TextUtils.isEmpty(
            mEtTradingPassword.text
        ) && !TextUtils.isEmpty(mEtConfirmTradingPassword.text))
    }

    override fun setView() {
        super.setView()
        //editText的左右padding不一致，目前只能在代码中设置，在xml中设置不支持rtl
        val dp16 = mContext.resources.getDimension(com.unionftech.common.R.dimen.dp_16).toInt()
        val dp48 = mContext.resources.getDimension(com.unionftech.common.R.dimen.dp_48).toInt()
        mEtInvitationCode.setPaddingRelative(dp16, 0, dp48, 0)
        mTvTradingPasswordError.autoSize(
            mContext.resources.getDimension(com.unionftech.common.R.dimen.sp_8).toInt(),
            mContext.resources.getDimension(com.unionftech.common.R.dimen.sp_10).toInt()
        )
        mTvConfirmTradingPasswordError.autoSize(
            mContext.resources.getDimension(com.unionftech.common.R.dimen.sp_8).toInt(),
            mContext.resources.getDimension(com.unionftech.common.R.dimen.sp_10).toInt()
        )
        hideCenterTitle()
        initTitleBar()
        loadData()
    }

    override fun loadData() {
        super.loadData()
        getPublicKey()
        queryPlatform(false)
    }

    private fun getPublicKey() {
        val publicKeyStr = GlobalInfoManager.getInstance().getPublicKeyStr()
        if (!TextUtils.isEmpty(publicKeyStr)) {
            mPublicKeyStr = publicKeyStr
        } else {
            GlobalInfoManager.getInstance().addListener(this)
            GlobalInfoManager.getInstance().update(GlobalInfoManager.UPDATE_PUBLIC_KEY)
        }
    }

    private fun initTitleBar() {
        setBackText(
            DynamicResourceManager.getString(string.add_live_account), mContext.resources.getColor(
                color.color_1C1D21
            )
        )
    }

    override fun doClick(v: View?) {
        super.doClick(v)
        when (v?.id) {
            R.id.et_trade_platform -> {
                //展示平台
                queryPlatform(true)
            }

            R.id.et_account_type -> {
                mEtInvitationCode.clearFocus()
                //展示账户类型
                queryAccountType(true)
            }

            R.id.et_account_currency -> {
                //展示币种
                queryCurrency()
            }

            R.id.iv_clear_trading_password -> mEtTradingPassword.setText("")
            R.id.iv_show_trading_password -> {
                if (mIvShowTradingPassword.isSelected) {
                    hidePasswordText(mEtTradingPassword, mIvShowTradingPassword)
                } else {
                    showPasswordText(mEtTradingPassword, mIvShowTradingPassword)
                }
            }

            R.id.iv_clear_confirm_trading_password -> mEtConfirmTradingPassword.setText("")
            R.id.iv_show_confirm_trading_password -> {
                if (mIvShowConfirmTradingPassword.isSelected) {
                    hidePasswordText(mEtConfirmTradingPassword, mIvShowConfirmTradingPassword)
                } else {
                    showPasswordText(mEtConfirmTradingPassword, mIvShowConfirmTradingPassword)
                }
            }

            R.id.iv_clear_invitation_code -> mEtInvitationCode.setText("")

            R.id.tv_invitation_code_title, R.id.iv_invitation_arrow -> {
                // 开始过渡动画
                TransitionManager.beginDelayedTransition(mRlInvitationCode)
                //展示隐藏邀请码
                mRlInvitationCode.visibility = if (mRlInvitationCode.isShown) {
                    startAnimation(mIvInvitationArrow, -180f, 0f)
                    mEtInvitationCode.setText("")
                    mTvInvitationCodeError.visibility = View.INVISIBLE
                    mEtInvitationCode.isSelected = false

                    View.GONE
                } else {
                    startAnimation(mIvInvitationArrow, 0f, -180f)
                    scrollPageDown()
                    View.VISIBLE
                }
            }

            R.id.btn_confirm -> {
                submit()
            }
        }
    }

    private fun scrollPageDown() {
        mScPage.post {
            mScPage.fullScroll(View.FOCUS_DOWN)
        }
    }

    private fun queryCurrency() {
        if (mPlatformIndex == -1 || mPlatformList.isEmpty()) {
            return
        }
        mPlatformList.getOrNull(mPlatformIndex)?.also { platform ->
            val userToken = GlobalInfoManager.getInstance().getUserToken()
            GlobalInfoManager.getInstance().getSystemUserInfo()?.also { userInfo ->
                mCommonPresenter.queryCurrency(
                    userToken, userInfo.residence, platform.platform.toString(), tradeType = "1"
                )
            }
        }
    }

    private fun queryAccountType(showDialog: Boolean) {
        mIsShowSelectDialog = showDialog
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        val inputInvitationCode = mEtInvitationCode.text.toString()
        var code = inputInvitationCode
        if (TextUtils.isEmpty(inputInvitationCode)) {
            code = GlobalInfoManager.getInstance().getSystemUserInfo()?.invitationCode ?: ""
        }
        mCommonPresenter.queryAccountType(userToken, code)
    }

    private fun queryPlatform(showDialog: Boolean) {
        mSystemPlatformList = null
        mGroupInfo = null
        val userToken = GlobalInfoManager.getInstance().getUserToken()
        val inputInvitationCode = mEtInvitationCode.text.toString()
        var code = inputInvitationCode
        if (TextUtils.isEmpty(inputInvitationCode)) {
            code = GlobalInfoManager.getInstance().getSystemUserInfo()?.invitationCode ?: ""
        }
        mCommonPresenter.queryPlatform(userToken, code)
        mCommonPresenter.queryGroupAndCurrency(userToken, code)
        mIsShowSelectDialog = showDialog
    }

    private fun hidePasswordText(editText: EditText, showValueView: ImageView) {
        showValueView.isSelected = false
        showValueView.setImageResource(drawable.icon_eye_off)
        editText.transformationMethod = PasswordTransformationMethod.getInstance()
        editText.setSelection(editText.text.length)
    }

    private fun showPasswordText(editText: EditText, showValueView: ImageView) {
        showValueView.isSelected = true
        showValueView.setImageResource(drawable.icon_eye_on)
        editText.transformationMethod = HideReturnsTransformationMethod.getInstance()
        editText.setSelection(editText.text.length)
    }

    private fun startAnimation(view: View, from: Float, to: Float) {
        val animation = RotateAnimation(
            from, to, view.width / 2f, view.height / 2f
        ).apply {
            duration = 300
            fillAfter = true
        }
        view.startAnimation(animation)
    }

    private fun checkAndShowPlatformDialog() {
        if (mSystemPlatformList != null && mGroupInfo != null) {
            //展示无效的邀请码
            if (!mGroupInfo!!.check && mRlInvitationCode.isShown && !TextUtils.isEmpty(
                    mEtInvitationCode.text
                )
            ) {
                scrollPageDown()
                mTvInvitationCodeError.text =
                    DynamicResourceManager.getString(string.invitation_code_invalid)
                mTvInvitationCodeError.visibility = View.VISIBLE
                mEtInvitationCode.isSelected = true
                return
            }
            //如果此次邀请码有效并且和上次的邀请码不同，则清除数据
            if (!TextUtils.isEmpty(mEtInvitationCode.text) && !TextUtils.equals(
                    mEtInvitationCode.text, mCurrentInvitationCode
                )
            ) {
                mCurrentInvitationCode = mEtInvitationCode.text.toString()
                resetData()
            }
            mPlatformList.clear()
            //首先根据mGroupInfo中的platform展示
            if (mGroupInfo!!.platform != null) {
                when (mGroupInfo!!.platform) {
                    PLATFORM_MT4 -> {
                        mPlatformList.add(TradePlatform(PLATFORM_MT4))
                    }

                    PLATFORM_MT5 -> {
                        mPlatformList.add(TradePlatform(PLATFORM_MT5))
                    }
                }
            } else {
                //如果 platform为null,并且 platformLimit为true,展示暂无平台可选
                if (!mGroupInfo!!.platformLimit) {
                    //展示mPlatformResult中的交易平台
                    for (platform in mSystemPlatformList!!) {
                        if (platform.platform == PLATFORM_MT4) {
                            mPlatformList.add(TradePlatform(PLATFORM_MT4))
                        }
                        if (platform.platform == PLATFORM_MT5) {
                            mPlatformList.add(TradePlatform(PLATFORM_MT5))
                        }
                    }
                }
            }
            //判断展示无平台可选
            val noCurrency = DynamicResourceManager.getString(string.no_currency_select)
            if (mPlatformList.isEmpty()) {
                mEtTradePlatform.isEnabled = false
                mEtTradePlatform.text = DynamicResourceManager.getString(string.no_platform_select)
                mPlatformIndex = -1
                mEtAccountCurrency.text = noCurrency
                mCurrencyIndex = -1
                mCurrencyList.clear()
                return
            }
            mEtTradePlatform.isEnabled = true
            //如果有平台可选，去除"暂无币种"的展示
            if (noCurrency == mEtAccountCurrency.text) {
                mEtAccountCurrency.text = ""
            }
            if (mIsShowSelectDialog) {
                //展示选择平台的弹框
                mIsShowSelectDialog = false
                showPlatformDialog()
            } else {
                //默认展示
                mPlatformIndex = mPlatformList.indexOf(TradePlatform(PLATFORM_MT5))
                if (mPlatformIndex == -1) {
                    mPlatformList.getOrNull(0)?.also {
                        mPlatformIndex = 0
                    }
                }
                setPlatformText(mPlatformIndex)
            }
        }
    }

    private fun resetData() {
        mPlatformIndex = -1
        mEtTradePlatform.text = ""
        mAccountTypeIndex = -1
        mEtAccountType.text = ""
        mCurrencyIndex = -1
        mEtAccountCurrency.text = ""
        setButtonEnable()
    }

    private fun setPlatformText(index: Int) {
        mPlatformList.getOrNull(index)?.also { result ->
            if (result.platform == Platform.MT5.platform) {
                mEtTradePlatform.text = Platform.MT5.desc
            } else if (result.platform == Platform.MT4.platform) {
                mEtTradePlatform.text = Platform.MT4.desc
            }
        }
    }

    private fun showPlatformDialog() {
        if (mPlatformList.isEmpty()) {
            return
        }
        val list = mutableListOf<String>()
        for (platform in mPlatformList) {
            if (platform.platform == Platform.MT4.platform) {
                list.add(Platform.MT4.desc)
            } else if (platform.platform == Platform.MT5.platform) {
                list.add(Platform.MT5.desc)
            }
        }
        val dialog = CustomSelectDialog(mContext)
        dialog.setTitle(DynamicResourceManager.getString(string.trading_platform))
            .setSelectIndex(mPlatformIndex)
            .setItemData(list)
            .setCallBack { index ->
                list.getOrNull(index)?.also { result ->
                    mEtTradePlatform.text = result
                    mPlatformIndex = index
                    setButtonEnable()
                }
            }.show()
    }

    private fun checkAndShowCurrencyDialog() {
        if (mSystemCurrencyList != null && mGroupInfo != null) {
            mCurrencyList.clear()
            if (TextUtils.isEmpty(mGroupInfo?.currency)) {
                //展示系统支持的币种
                mCurrencyList.addAll(mSystemCurrencyList!!)
            } else {
                mCurrencyList.add(mGroupInfo!!.currency)
            }
            showCurrencyDialog()
        }
    }

    private fun showAccountTypeDialog() {
        val list = mutableListOf<String>()
        for (accountType in mAccountTypeList) {
            if (AccountType.ECN.accountType == accountType) {
                list.add(DynamicResourceManager.getString(AccountType.ECN.stringId))
            } else if (AccountType.STP.accountType == accountType) {
                list.add(DynamicResourceManager.getString(AccountType.STP.stringId))
            }
        }
        val dialog = CustomSelectDialog(mContext)
        dialog.setTitle(DynamicResourceManager.getString(string.trading_account_type))
            .setSelectIndex(mAccountTypeIndex).setItemData(list).setCallBack { index ->
                list.getOrNull(index)?.also { result ->
                    mEtAccountType.text = result
                    mAccountTypeIndex = index
                    setButtonEnable()
                }
            }.show()
    }

    private fun showCurrencyDialog() {
        if (mCurrencyList.isEmpty()) {
            return
        }
        val dialog = CustomSelectDialog(mContext)
        dialog.setTitle(DynamicResourceManager.getString(string.account_currency))
            .setSelectIndex(mCurrencyIndex).setItemData(mCurrencyList).setCallBack { index ->
                mCurrencyList.getOrNull(index)?.also { result ->
                    mEtAccountCurrency.text = result
                    mCurrencyIndex = index
                    setButtonEnable()
                }
            }.show()
    }

    private fun submit() {
        //检查邀请码的有效性
        val inputCode = mEtInvitationCode.text.toString()
        if (!TextUtils.isEmpty(inputCode) && !TextUtils.equals(inputCode, mCurrentInvitationCode)) {
            //清除焦点，然后重新获取邀请码所支持的平台
            mEtInvitationCode.clearFocus()
            return
        }
        getRequestBean()?.also { request ->
            val userToken = GlobalInfoManager.getInstance().getUserToken()
            mAccountPresenter.createLiveAccount(userToken, request)
        }
    }

    private fun getRequestBean(): AddLiveAccountRequest? {
        if (mPlatformIndex == -1) {
            return null
        }
        if (mAccountTypeIndex == -1) {
            return null
        }
        if (mCurrencyIndex == -1) {
            return null
        }
        if (!checkInput(mEtTradingPassword)) {
            return null
        }
        if (!checkInput(mEtConfirmTradingPassword)) {
            return null
        }
        if (!TextUtils.equals(mEtTradingPassword.text, mEtConfirmTradingPassword.text)) {
            return null
        }
        val request = AddLiveAccountRequest().apply {
            mPlatformList.getOrNull(mPlatformIndex)?.also { result ->
                platform = result.platform
            }
            mAccountTypeList.getOrNull(mAccountTypeIndex)?.also { result ->
                accountType = result
            }
            mCurrencyList.getOrNull(mCurrencyIndex)?.also { result ->
                accountCoinType = result
            }
            SignUtils.encrypt(
                SignUtils.loadPublicKeyByStr(mPublicKeyStr),
                mEtConfirmTradingPassword.text.toString().toByteArray()
            )?.also {
                traderPassword = it
            }
            sameRemark = mEtRemark.text.toString()
            val inputInvitationCode = mEtInvitationCode.text.toString()
            var code = inputInvitationCode
            if (TextUtils.isEmpty(inputInvitationCode)) {
                code = GlobalInfoManager.getInstance().getSystemUserInfo()?.invitationCode ?: ""
            }
            invitationCode = code
        }
        return request
    }

    /**
     * 获取系统默认支持的平台
     */
    override fun handlePlatformView(response: ResponseResult<List<TradePlatform>>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            response.data?.also {
                mSystemPlatformList = it
                checkAndShowPlatformDialog()
            }
        } else {
            LogUtils.d(TAG, "handlePlatformView error-> $response")
            response.toast()
        }
    }


    /**
     * 根据邀请码获取交易组的支持的平台
     */
    override fun handleGroupCurrencyView(response: ResponseResult<UserGroupInfo>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            response.data?.also {
                mGroupInfo = it
                //综合展示平台
                checkAndShowPlatformDialog()
            }
        } else {
            LogUtils.d(TAG, "handleGroupCurrencyView error-> $response")
            response.toast()
        }
    }


    /**
     * 根据邀请码获取交易组支持的币种
     */
    override fun handleCurrencyView(response: ResponseResult<List<String>>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            response.data?.also {
                mSystemCurrencyList = it
                checkAndShowCurrencyDialog()
            }
        } else {
            LogUtils.d(TAG, "handleCurrencyView error-> $response")
            response.toast()
        }
    }

    /**
     * 获取账号类型
     */
    override fun handleAccountTypeView(response: ResponseResult<List<Int>>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            response.data?.also {
                mAccountTypeList.clear()
                mAccountTypeList.addAll(it)
                //如果选项中不包含已选择的账号类型，需要清除
                val selectAccountType = mAccountTypeList.getOrNull(mAccountTypeIndex)
                if (selectAccountType == null) {
                    mEtAccountType.text = ""
                    mAccountTypeIndex = -1
                }
                if (mIsShowSelectDialog) {
                    mIsShowSelectDialog = false
                    showAccountTypeDialog()
                }
            }
        } else {
            LogUtils.d(TAG, "handleAccountTypeView error->$response")
            response.toast()
        }
    }

    /**
     * 获取创建真实账户的结果
     */
    override fun handleAddLiveAccount(response: ResponseResult<Any?>) {
        if (response.code == ResponseResult.SUCCESS_CODE) {
            showApplySuccessDialog()
            GlobalInfoManager.getInstance()
                .notify(LiveAccountListFragment::class.java, GlobalInfoManager.UPDATE_LIVE_LIST)
            GlobalInfoManager.getInstance()
                .notify(HomeFragment::class.java, GlobalInfoManager.UPDATE_LIVE_LIST)
        } else {
            LogUtils.d(TAG, "handleAddLiveAccount error->$response")
            response.toast()
        }
    }

    private fun showApplySuccessDialog() {
        val tipDialog = CustomTipDialog(mContext)
        tipDialog.setTopRes(R.drawable.ic_circle_success)
            .setTitle(DynamicResourceManager.getString(string.application_successful))
            .setMessage(DynamicResourceManager.getString(string.please_wait_tips))
            .setConfirmText(DynamicResourceManager.getString(string.close)).setCallBack {
                finish()
            }.show()
    }

    override fun onUpdate(obj: Any?) {
        when (obj) {
            is String -> {
                mPublicKeyStr = obj
            }
        }
    }

    override fun backPressed(): Boolean {
        showLeaveDialog()
        return true
    }

    /**
     * 屏蔽物理返回键
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    private fun showLeaveDialog() {
        val dialog = CustomTipDialog(mContext)
        dialog.setTopRes(R.drawable.ic_circle_warning)
            .setTitle(DynamicResourceManager.getString(mContext, string.confirm_leave))
            .setCancelText(
                DynamicResourceManager.getString(
                    mContext, string.cancel
                )
            ).setConfirmText(
                DynamicResourceManager.getString(
                    mContext, string.confirm
                )
            ).setCallBack { confirm ->
                if (confirm) {
                    finish()
                }
                dialog.dismiss()
            }.show()
    }

    override fun onDestroy() {
        GlobalInfoManager.getInstance().remove(this)
        super.onDestroy()
    }


}